<?php

require __DIR__.'/ErrorCode.php';
class User
{
    /**
     * 数据库连接句柄
     * @var
     */
    private $_db;

    public function __construct($_db)
    {
        $this->_db = $_db;
    }

    /**
     * 用户登录
     * @param $username
     * @param $password
     */
    public function login($username, $password)
    {
        if( empty($username) ){
            throw new Exception('用户名不能为空',ErrorCode::USERNAME_CANNOT_EMPTY);
        }

        if( empty($password) ){
            throw new Exception('密码不能为空',ErrorCode::PASSWORD_CANNOT_EMPTY);
        }

        $sql = 'select * from `user` where `username`=:username and `password` = :password';
        $password = $this->_md5($password);
        $stmt = $this->_db->prepare($sql);
        $stmt->bindParam(':username',$username);
        $stmt->bindParam(':password',$password);
        $stmt->execute();
        if( !$stmt->execute() ){
            throw new Exception('服务器内部错误',ErrorCode::SERVER_INTERNAL_ERROR);
        }
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if( empty($user) ){
            throw new Exception('用户名或密码错误',ErrorCode::USERNAME_OR_PASSWORD_INVALID);
        }

        unset($user['password']);
        return $user;


    }

    /**
     * 用户注册
     * @param $username
     * @param $password
     */
    public function register($username,$password)
    {
        if( empty($username) ){
            throw new Exception('用户名不能为空',ErrorCode::USERNAME_CANNOT_EMPTY);
        }

        if( empty($password) ){
            throw new Exception('密码不能为空',ErrorCode::PASSWORD_CANNOT_EMPTY);
        }

        if( $this->_isUserNameExists($username) ){
            throw new Exception('用户名已存在',ErrorCode::USERNAME_EXISTS);
        }

        //写入数据库
        $sql = 'insert into `user`(`username`,`password`,`created_at`) values(:username,:password,:created_at)';
        $date_now = date('Y-m-d H:i:s');
        $stmt = $this->_db->prepare($sql);
        $password = $this->_md5($password);
        $stmt->bindParam(':username',$username);
        $stmt->bindParam(':password',$password);
        $stmt->bindParam(':created_at',$date_now);
        if( !$stmt->execute() ){
            throw new Exception('注册失败',$stmt->errorCode(),ErrorCode::REGISTER_FAIL);
        }
        return [
            'userId' => $this->_db->lastInsertId(),
            'username' => $username,
            'created_at' => $date_now
        ];
    }

    private function _md5($password)
    {
        $key = 'alan';
        return md5($password.$key);
    }

    private function _isUserNameExists($username)
    {
        $sql = 'SELECT * FROM `user` WHERE `username` = :username';
        $stmt = $this->_db->prepare($sql);
        $stmt->bindParam(':username',$username);
        $stmt->execute();
        $result =   $stmt->fetch(PDO::FETCH_ASSOC);
        return !empty($result);

    }
}